package com.badboy.servlet;

import com.badboy.entity.Users;
import com.badboy.mapper.PostsMapper;
import com.badboy.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
    // 数据库连接信息
    private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database";
    private static final String DB_USER = "username";
    private static final String DB_PASSWORD = "password";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        PrintWriter out = resp.getWriter();
        String postId = req.getParameter("postId");

        // 从session中获取用户ID
        HttpSession session = req.getSession();
        Users user = (Users) session.getAttribute("user");

        Integer userId = user.getUserId();

        if (postId == null || userId == null) {
            out.print("{\"success\": false, \"message\": \"参数缺失或未登录\"}");
            return;
        }

        try {
            // 1. 检查用户是否是管理员
            boolean isAdmin = user.getIsAdmin().equals(1);

            if (!isAdmin) {
                out.print("{\"success\": false, \"message\": \"无权限删除\"}");
                return;
            }

            // 2. 执行删除操作

            if (deletePost(postId)>0) {
                out.print("{\"success\": true, \"message\": \"删除成功\"}");
            } else {
                out.print("{\"success\": false, \"message\": \"删除失败，帖子可能不存在\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\": false, \"message\": \"服务器错误: " + e.getMessage() + "\"}");
        }
    }

    private boolean checkIfAdmin(String userId) throws Exception {
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            String sql = "SELECT is_admin FROM users WHERE user_id = ?";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, userId);
                ResultSet rs = stmt.executeQuery();
                return rs.next() && rs.getBoolean("is_admin");
            }
        }
    }

    private int deletePost(String postId) throws Exception {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        PostsMapper postsMapper = sqlSession.getMapper(PostsMapper.class);
        return postsMapper.deleteByPrimaryKey(Long.valueOf(postId));
    }
}